package com.wmh.baseservice.operationaid.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wmh.baseservice.common.ex.ServiceException;
import com.wmh.baseservice.common.mybatisplus.structure.LambdaQueryWrapperX;
import com.wmh.baseservice.common.utils.web.UserUtil;
import com.wmh.baseservice.operationaid.entity.KeyWordUsageRecordGroup;
import com.wmh.baseservice.operationaid.mapper.KeyWordUsageRecordGroupMapper;
import com.wmh.baseservice.operationaid.pojo.vo.keyWordUsageRecordGroup.KeyWordCreateGroupReqVO;
import com.wmh.baseservice.operationaid.pojo.vo.keyWordUsageRecordGroup.KeyWordUpdateGroupReqVO;
import com.wmh.baseservice.operationaid.service.KeyWordUsageRecordGroupService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 谢骏
 * @description 针对表【operation_aid_key_word_usage_record_group(关键词用途记录分组表)】的数据库操作Service实现
 * @createDate 2023-07-10 16:40:20
 */
@Service
public class KeyWordUsageRecordGroupServiceImpl extends ServiceImpl<KeyWordUsageRecordGroupMapper, KeyWordUsageRecordGroup>
        implements KeyWordUsageRecordGroupService {

    @Resource
    private UserUtil userUtil;

    @Override
    public void create(KeyWordCreateGroupReqVO reqVO) {
        Long adId = userUtil.getId();
        checkNameUniqueness(null, reqVO.getName(), reqVO.getCategoryName());
        KeyWordUsageRecordGroup entity = new KeyWordUsageRecordGroup()
                .setName(reqVO.getName()).setAdId(adId).setCategoryName(reqVO.getCategoryName());
        baseMapper.insert(entity);
    }

    @Override
    public void update(KeyWordUpdateGroupReqVO req) {
        checkNameUniqueness(req.getId(), req.getName(),req.getCategoryName());
        KeyWordUsageRecordGroup entity = new KeyWordUsageRecordGroup();
        entity.setAdId(userUtil.getId()).setName(req.getName()).setId(req.getId())
                .setCategoryName(req.getCategoryName());
        baseMapper.updateById(entity);
    }

    @Override
    public void remove(List<Long> ids) {
        baseMapper.delete(new LambdaQueryWrapperX<KeyWordUsageRecordGroup>()
                .in(KeyWordUsageRecordGroup::getId,ids));
    }

    private void checkNameUniqueness(Long id, String name,String categoryName) {
        KeyWordUsageRecordGroup entity = baseMapper.selectOne(new LambdaQueryWrapperX<KeyWordUsageRecordGroup>()
                .neIfPresent(KeyWordUsageRecordGroup::getId, id)
                .eq(KeyWordUsageRecordGroup::getName, name)
                .eq(KeyWordUsageRecordGroup::getAdId, userUtil.getId())
                .eq(KeyWordUsageRecordGroup::getCategoryName,categoryName)
        );
        if (entity != null) {
            throw new ServiceException("名称重复");
        }
    }
}




